/********************************************************************************
 * Copyright(c) 2020-2025 BST All rights reserved.
 * - Filename
 * - Author
 * - Version V1.0.0
 * - Date    2025/08/05
 * - Brief
 * - FunctionList:
 ******************************************************************************
 * History:
 *
 *
 *
 ******************************************************************************
 */

#include <condition_variable>
#include <csignal>
#include <fstream>
#include <iostream>
#include <mutex>

#include "CommonUtil.hpp"
#include "DhopReplayFrame.pb.h"
#include "FileReader.hpp"
#include "hv/base64.h"
#include "vzmq.hpp"
#include "Logger.hpp"

static std::mutex mExitMutex;
static std::condition_variable mExitCond;
static bool mExit = false;

static void sigtermHandler(int sig) {
  {
    std::lock_guard<std::mutex> lock(mExitMutex);
    mExit = true;
  }
  mExitCond.notify_one();
}

static void waitForExit() {
  mExit = false;
  signal(SIGHUP, SIG_IGN);          // 连接挂断
  signal(SIGQUIT, SIG_IGN);         // 终端退出
  signal(SIGPIPE, SIG_IGN);         // 向无读进程的管道写数据
  signal(SIGTTOU, SIG_IGN);         // 后台程序尝试写操作
  signal(SIGTTIN, SIG_IGN);         // 后台程序尝试读操作
  signal(SIGTERM, sigtermHandler);  // 终止
  signal(SIGINT, sigtermHandler);   // 终端中
  std::unique_lock<std::mutex> lock(mExitMutex);
  mExitCond.wait(lock, [&] { return mExit; });
}

#include <fstream>
#include <vector>

bool write_jpeg_file(const std::string& filename,
                     const std::vector<unsigned char>& jpeg_buffer) {
  // 创建输出文件流（二进制模式 | 覆盖写入）
  std::ofstream out_file(filename, std::ios::binary | std::ios::trunc);

  if (!out_file.is_open()) {
    return false;  // 文件打开失败
  }

  // 写入整个缓冲区
  out_file.write(reinterpret_cast<const char*>(jpeg_buffer.data()),
                 jpeg_buffer.size());

  // 检查写入是否成功
  return out_file.good();
}

int main(int argc, const char* argv[]) {
  auto context = std::make_shared<vzmq::VzmqContext>();
  auto imageRecive = context->createSubscribler<ImageFrame>(
      REPLAY_IMAGE_FRAME_CHANNAL_SUB,
      [](const std::shared_ptr<ImageFrame>& frame) {
        LOGI("time:%d,data:%ld", frame->timestamp(), frame->data().size());
        std::string imageStr =
            hv::Base64Decode(frame->data().c_str(), frame->data().size());
        std::vector<unsigned char> jpegData;
        jpegData.resize(imageStr.size());
        memcpy(&jpegData[0], (uint8_t*)imageStr.c_str(), imageStr.size());
        std::string name = std::to_string(frame->timestamp()) + ".jpeg";
        write_jpeg_file(name, jpegData);
      });
  waitForExit();
}